package com.aiwei.tdjk.controller.sys;


import com.aiwei.tdjk.bean.Pager;
import com.aiwei.tdjk.common.Constants;
import com.aiwei.tdjk.controller.BaseController;
import com.aiwei.tdjk.dto.request.GetGroupPagerRequest;
import com.aiwei.tdjk.dto.request.GetGroupRelationPagerRequest;
import com.aiwei.tdjk.entity.Group;
import com.aiwei.tdjk.entity.GroupRelation;
import com.aiwei.tdjk.enums.BooleanEnum;
import com.aiwei.tdjk.enums.GroupTypeEnum;
import com.aiwei.tdjk.service.GroupRelationService;
import com.aiwei.tdjk.service.GroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;
import java.util.Set;

/**
 * <p>User: yanfeng
 * <p>Date: 13-1-28 下午4:29
 * <p>Version: 1.0
 */
@Controller
@RequestMapping(value = "/admin/sys/group")
public class GroupController extends BaseController<Group> {

    @Autowired
    private GroupService groupService;

    @Autowired
    private GroupRelationService groupRelationService;


    protected void setCommonData(Model model) {
        model.addAttribute("types", GroupTypeEnum.values());
        model.addAttribute("booleanList", BooleanEnum.values());
    }


    @RequestMapping(method = RequestMethod.GET)
    public String list(GetGroupPagerRequest request, Model model) {
        model.addAttribute("page", groupService.find(request));
        setCommonData(model);
        model.addAttribute("m", request);
        return viewName("list");
    }


    @RequestMapping(value = "{type}/list", method = RequestMethod.GET)
    public String list(GetGroupPagerRequest request,@PathVariable("type") String type,Model model) {
        request.setType(type);
        setCommonData(model);
        return list(request,model);
    }

    /**
     * 仅返回表格数据
     *
     * @param model
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, headers = "table=true")
    public String listTable(GetGroupPagerRequest request,Model model) {
//        list(searchable, model);
        return viewName("listTable");
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String view(Model model, @PathVariable("id") Long id) {
        setCommonData(model);
        model.addAttribute("m", groupService.get(id));
        model.addAttribute(Constants.OP_NAME, "查看");
        return viewName("editForm");
    }

    @RequestMapping(value = "create", method = RequestMethod.GET)
    public String showCreateForm(Model model) {
        setCommonData(model);
        model.addAttribute(Constants.OP_NAME, "新增");
        if (!model.containsAttribute("m")) {
            model.addAttribute("m", new Group());
        }
        return viewName("editForm");
    }


    @RequestMapping(value = "create", method = RequestMethod.POST)
    public String create(Model model, @ModelAttribute("m") Group m, RedirectAttributes redirectAttributes,
                         @RequestParam(value = "domicileId", required = false) Long[][] domicileIds) {

//        if (hasError(m, result)) {
//            return showCreateForm(model);
//        }
//        m.setType(GroupTypeEnum.getValue(m.getType()).name());
        groupService.save(m);

        redirectAttributes.addFlashAttribute(Constants.MESSAGE, "新增成功");
        return redirectToUrl("");
    }

    @RequestMapping(value = "{type}/create", method = RequestMethod.GET)
    public String showCreateFormWithType(@PathVariable("type") Integer type, Model model) {
        if (!model.containsAttribute("m")) {
            Group group = new Group();
            group.setDefaultGroup(false);
            group.setIsShow(true);
            group.setType(type.byteValue());
            model.addAttribute("m", group);
        }
        return showCreateForm(model);
    }

    @RequestMapping(value = "{type}/create", method = RequestMethod.POST)
    public String create(
            Model model, @Valid @ModelAttribute("m") Group m, BindingResult result,
            @RequestParam(value = "domicileId", required = false) Long[][] domicileIds,
            RedirectAttributes redirectAttributes) {

        return create(model, m, redirectAttributes,domicileIds);
    }


    @RequestMapping(value = "{id}/update", method = RequestMethod.GET)
    public String showUpdateForm(@PathVariable("id") Long id, Model model) {

        setCommonData(model);
        model.addAttribute(Constants.OP_NAME, "修改");
        model.addAttribute("m", groupService.get(id));
        return viewName("editForm");
    }

    @RequestMapping(value = "{id}/update", method = RequestMethod.POST)
    public String update(Group group,Model model,
            @RequestParam(value = "domicileId", required = false) Long[][] domicileIds,
            RedirectAttributes redirectAttributes) {
//        if (hasError(m, result)) {
//            return showUpdateForm(m, model);
//        }
        groupService.update(group);

        redirectAttributes.addFlashAttribute(Constants.MESSAGE, "修改成功");
        return redirectToUrl("");
    }

    @RequestMapping(value = "{id}/delete", method = RequestMethod.GET)
    public String showDeleteForm(@PathVariable("id") Long id, Model model) {

        setCommonData(model);
        model.addAttribute(Constants.OP_NAME, "删除");
        model.addAttribute("m", groupService.get(id));
        return viewName("editForm");
    }

    @RequestMapping(value = "{id}/delete", method = RequestMethod.POST)
    public String delete(
            @PathVariable("id") long id,
            @RequestParam(value = Constants.BACK_URL, required = false) String backURL,
            RedirectAttributes redirectAttributes) {

        groupService.delete(id);

        redirectAttributes.addFlashAttribute(Constants.MESSAGE, "删除成功");
        return redirectToUrl("");
    }

    @RequestMapping(value = "batch/delete", method = {RequestMethod.GET, RequestMethod.POST})
    public String deleteInBatch(
            @RequestParam(value = "ids", required = false) Long[] ids,
            @RequestParam(value = Constants.BACK_URL, required = false) String backURL,
            RedirectAttributes redirectAttributes) {

        groupService.delete(ids);
        redirectAttributes.addFlashAttribute(Constants.MESSAGE, "删除成功");
        return redirectToUrl("");
    }


    @RequestMapping(value = "/changeStatus/{newStatus}")
    public String changeShowStatus(
            HttpServletRequest request,
            @PathVariable("newStatus") Boolean newStatus,
            @RequestParam("ids") Long[] ids) {

        for (Long id : ids) {
            Group group = groupService.get(id);
            group.setIsShow(newStatus);
            groupService.update(group);
        }
        return redirectToUrl("");
    }


    @RequestMapping(value = "/changeDefaultGroup/{newStatus}")
    public String changeDefaultGroup(
            HttpServletRequest request,
            @PathVariable("newStatus") Boolean newStatus,
            @RequestParam("ids") Long[] ids) {

        for (Long id : ids) {
            Group group = groupService.get(id);
            if (!group.getType().equals(GroupTypeEnum.user.name()) ) {//只有用户组 可设置为默认 其他无效
                continue;
            }
            group.setDefaultGroup(newStatus);
            groupService.update(group);
        }
        return redirectToUrl("");
    }

   @RequestMapping("ajax/autocomplete")
    @ResponseBody
    public Set<Map<String, Object>> autocomplete(String searchType,@RequestParam("term") String term) {
        return groupService.findIdAndNames(searchType,term);
    }


    ///////////////////////////////分组 内//////////////////////////////////////
    @RequestMapping(value = "/{groupId}/listRelation", method = RequestMethod.GET)
    public String listGroupRelation(GetGroupRelationPagerRequest request, Model model) {

        Group group = groupService.get(request.getGroupId());

        Pager<GroupRelation> groupRelationPager = null;

        if (group.getType() == GroupTypeEnum.user.getCode().byteValue()) {
            groupRelationPager = groupRelationService.findAllByGroupId(request);
        }

        if (group.getType() == GroupTypeEnum.organization.getCode().byteValue()) {
            groupRelationPager = groupRelationService.findAllByGroupId(request);
        }

        model.addAttribute("page", groupRelationPager);
        model.addAttribute("m", request);
        model.addAttribute("group", group);
        return viewName("relation/relationList");
    }


//    @RequestMapping(value = "/{group}/listRelation", headers = "table=true", method = RequestMethod.GET)
//    @PageableDefaults(sort = "id=desc")
//    public String listGroupRelationTable(@PathVariable("group") Group group, Searchable searchable, Model model) {
//
//        this.permissionList.assertHasViewPermission();
//
//        this.listGroupRelation(group, searchable, model);
//        return viewName("relation/relationListTable");
//
//    }
//
    @RequestMapping(value = "{group}/batch/delete", method = RequestMethod.GET)
    public String batchDeleteGroupRelation(
            @PathVariable("group") Long groupId,
            @RequestParam("ids") Long[] ids,
            @RequestParam(value = Constants.BACK_URL, required = false) String backURL,
            RedirectAttributes redirectAttributes) {

        Group group = groupService.get(groupId);
        if (group.getType() == GroupTypeEnum.user.getCode().byteValue()) {
            groupRelationService.delete(ids);
        }

        if (group.getType() == GroupTypeEnum.organization.getCode().byteValue()) {
            groupRelationService.delete(ids);
        }

        redirectAttributes.addFlashAttribute(Constants.MESSAGE, "删除成功");
        return redirectToUrl(groupId+"/listRelation");

    }

    @RequestMapping(value = "{group}/batch/append", method = RequestMethod.GET)
    public String showBatchAppendGroupRelationForm(@PathVariable("group") Long groupId,Model model) {
        Group group = groupService.get(groupId);
        model.addAttribute("group",group);
        if (group.getType() == GroupTypeEnum.user.getCode().byteValue()) {
            return viewName("relation/appendUserGroupRelation");
        }

        if (group.getType() == GroupTypeEnum.organization.getCode().byteValue()) {
            return viewName("relation/appendOrganizationGroupRelation");
        }

        throw new RuntimeException("group type error");
    }

    @RequestMapping(value = "{group}/batch/append", method = RequestMethod.POST)
    public String batchAppendGroupRelation(
            Model model,
            @PathVariable("group") Long groupId,
            @RequestParam("ids") Long[] ids,
            //只有用户组 有fromIds endIds
            @RequestParam(value = "startIds", required = false) Long[] startIds,
            @RequestParam(value = "endIds", required = false) Long[] endIds,
            @RequestParam(value = Constants.BACK_URL, required = false) String backURL,
            RedirectAttributes redirectAttributes) {

        Group group = groupService.get(groupId);
        model.addAttribute("group",group);

        if (group.getType() == GroupTypeEnum.organization.getCode().byteValue()) {
            groupRelationService.appendRelation(group.getId(), ids);
        }

        if (group.getType() == GroupTypeEnum.user.getCode().byteValue()) {
            groupRelationService.appendRelation(group.getId(), ids, startIds, endIds);
        }


        redirectAttributes.addFlashAttribute(Constants.MESSAGE, "批量添加成功");

        return redirectToUrl(groupId+"/listRelation");
    }


}
